package com.zxlspace.Chapter1.controller;

import com.zxlspace.Chapter1.pojo.Result;
import com.zxlspace.Chapter1.repository.GirlRepository;
import com.zxlspace.Chapter1.pojo.Girl;
import com.zxlspace.Chapter1.service.GirlService;
import com.zxlspace.Chapter1.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author zhangxiaolin@zhonhajt.com
 * @Title:
 * @Package com.zxlspace.Chapter1.controller
 * @Description:
 * @date 2018/6/8 14:19
 */
@RestController
public class GirlController {
    Logger logger = LoggerFactory.getLogger(GirlController.class);

    @Autowired
    private GirlRepository girlRepository;

    @Autowired
    private GirlService girlService;

    //查询全部
    @GetMapping(value = "/girls")
    public List<Girl> getGirls() {
        return girlRepository.findAll();
    }

    //新增
    @PostMapping(value = "/girls")
    public Result<Girl> postGirls(@ModelAttribute @Valid Girl girl, BindingResult bindingResult) {
        logger.info("新增用户: {}", girl);

        if (bindingResult.hasErrors()) {
            System.out.println("当前参数出现错误：" + bindingResult.getFieldError().getDefaultMessage());
            return ResultUtil.error(1, bindingResult.getFieldError().getDefaultMessage());
        }

        return ResultUtil.success( girlRepository.save(girl));
    }

    //新增
    @PostMapping(value = "/girls/add")
    public Girl addGirls(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age) {
        Girl girl = new Girl();
        girl.setAge(age);
        girl.setCupSize(cupSize);

        return girlRepository.save(girl);
    }

    //查询单个
    @GetMapping(value = "/girls/{id}")
    public Girl getGirlsById(@PathVariable Integer id) {
        return girlRepository.findOne(id);
    }

    //更新单个
    @PutMapping(value = "/girls/${id}")
    public Girl postGirls(@PathVariable Integer id, Girl girl) {
        Girl girlQ = girlRepository.findOne(id);
        girlQ.setCupSize(girl.getCupSize());
        girlQ.setAge(girl.getAge());
        return girlRepository.save(girlQ);
    }

    //删除用户
    @DeleteMapping(value = "/girls/{id}")
    public String postGirls(@PathVariable Integer id) {
        if (!StringUtils.isEmpty(id)) {
            girlRepository.delete(id);
        }
        return "success";
    }

    /**
     * 通过年龄查询
     * @param age
     * @return
     */
    @GetMapping(value = "/girls/age/{age}")
    public List<Girl> queryGirlsByAge(@PathVariable Integer age) {
        return girlRepository.findByAge(age);
    }


    @GetMapping(value = "/girls/getAge/{id}")
    public void getAge(@PathVariable("id") Integer id) throws Exception {
        girlService.getAge(id);
    }
}
